<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-alert type="info">
        <template slot="message">
          <div>1.店铺授权成功提交保存后，默认获取平台前7天的历史订单数据，此过程同步数据时间较长，请耐心等待！</div>
          <div>2.成本中心新增成功后若需变更成本，<span style="color:#D9001B;">需次月生效</span></div>
        </template>
        </a-alert>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="平台名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <div class="platform-name">
                <div>
                  <span><img :src="amazonIcon" width="37px" height="37px" /> </span>
                  <span class="name-font">Amazon</span>
                </div>
                <div class="name-right">
                  <a @click="previewHandle"><a-icon type="exclamation-circle" />&nbsp;&nbsp;操作说明</a>
                </div>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <span slot="label">
                <a-tooltip>
                  <template slot="title">
                    此处表示店铺的名称前缀，系统内唯一，保存成功后，会自动按照此处填写的店铺名称+“_国家代号”自动生成店铺名称。
                  </template>
                   <span class="required-icon">*</span> 店铺名称 &nbsp; <a-icon type="info-circle" />
                </a-tooltip>
              </span>
              <a-input
                v-if="merchantType === '2'"
                v-model="model.name"
                placeholder="系统内唯一，添加后不可修改，不能包含\ / * ? ' :  <  > | 空格，. 且不超过32字符。"
                :disabled="model.id && !formDisabled"
                :maxLength="32"
              ></a-input>
              <a-select
                v-else
                show-search
                v-model="model.name"
                placeholder="请选择店铺名称"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                @search="handleSearch"
                :disabled="model.id && !formDisabled"
              >
                <a-select-option v-for="(store, index) in storeNameData" :key="index" :value="store">
                  {{ store }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="成本中心" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="costCenterId">
              <a-select v-model="model.costCenterId" placeholder="请选择成本中心" show-search option-filter-prop="children" :filter-option="filterOption">
                <a-select-option  v-for="(costCenter,index) in costCenterData" :key="index" :value="costCenter.id">{{costCenter.name}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="director">
              <j-search-select-tag
                v-model="model.director"
                placeholder="请输入并选择店铺负责人"
                :dictOptions="userDictOptions"
              >
              </j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="站点"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
              style="margin-bottom: 0"
            >
              <a-form-model-item prop="regionCode" style="width: 150px; display: inline-block">
                <a-select
                  v-model="model.regionCode"
                  placeholder="选择区域"
                  @change="regionChange"
                  :disabled="model.id && !formDisabled"
                >
                  <a-select-option v-for="regionCode in storeSiteOptions" :key="regionCode.code">
                    {{ regionCode.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item
                v-if="countryOptions && countryOptions.length > 0"
                prop="country"
                style="width: calc(100% - 150px); display: inline-block"
              >
                <a-select
                  mode="multiple"
                  v-model="model.country"
                  placeholder="选择国家"
                  :disabled="model.id && !formDisabled"
                  allowClear
                >
                  <a-select-option v-for="country in countryOptions" :key="country.code">
                    {{ country.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="model.regionCode && model.country && model.country.length >0">
            <a-form-model-item label="授权状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="authStatus">
              <!-- <j-dict-select-tag type="list" v-model="model.authStatus" dictCode="oms_store_auth_status" placeholder="请选择授权状态" /> -->
              <a-button type="primary" @click="authHandle">点击授权</a-button>
              <span class="tip">注：点击授权后将跳转到亚马逊卖家后台授权，为避免店铺关联，请在店铺常用环境操作</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="syncStatus">
              <span slot="label">
                <a-tooltip>
                  <template slot="title"> 选择停用后，系统不再从亚马逊店铺的当前站点下载订单至系统 </template>
                  同步状态 &nbsp; <a-icon type="info-circle" />
                </a-tooltip>
              </span>
              <j-dict-select-tag
                type="radio"
                v-model="model.syncStatus"
                dictCode="oms_store_sync_status"
                placeholder="请选择同步状态"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :rows="3" v-model="model.remark" placeholder="请输入备注" :maxLength="60" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction, putFormAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { randomUUID, simpleDebounce } from '@/utils/util'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import { Base64 } from 'js-base64'
export default {
  name: 'StoreAuthAmazonForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    storeSiteData: {    //站点国家数据源
      type: Array,
      default: () => [],
    },
    costCenterList:{      //成本中心
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      model: {
        syncStatus: '1', //同步状态默认启用
        authId: randomUUID(),
      },
      countryOptions: [], //国家数据
      merchantType: Vue.ls.get(USER_INFO).merchantType, //客户类型： 1：内部客户  2：外部客户
      storeNameData: [], //店铺名称数据
      userDictOptions: [], //负责人
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      amazonIcon: require('@/assets/oms/amazon.png'),
      authSkipUrl: '', //授权跳转地址
      searchOptions: [], //所属组织
      //costCenterData:[],   //成本中心
      validatorRules: {
        name: [{ validator: this.validatorName }],
        director: [{ required: true, message: '请选择授权站点负责人' }],
        costCenterId:[{required:true,message:'请选择成本中心'}],
        regionCode: [{ required: true, message: '请选择区域' }],
        country: [{ required: true, message: '请选择国家' }],
        syncStatus: [{ required: true, message: '请选择同步状态' }],
        remark: [{ pattern: /^.{0,60}$/, message: '请输入不超过60个文字' }],
      },
      url: {
        add: '/oms/store/storeAuthAmazon/add',
        edit: '/oms/store/storeAuthAmazon/edit',
        queryById: '/oms/store/storeAuthAmazon/queryById',
        authUrl: '/oms/openApi/amazon/authUrl',
        queryStoreName: '/oms/store/storeAuthAmazon/queryStoreName',
        getAllUsernameByOrg: '/sys/user/getAllUsernameByOrg',
        queryTreeListByCurrDepart: '/sys/sysDepart/queryTreeListByCurrDepart',
        downloadAuthStep:'/oms/store/storeAuthAmazon/downloadAuthStep',
        queryAllByOrgCode:'/sys/costCenter/queryAllByOrgCode',
      },
      replaceFields: {
        key: 'key',
        title: 'departName',
        children: 'children',
        value: 'orgCode',
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    storeSiteOptions() {
      return this.storeSiteData
    },
    costCenterData(){
      return this.costCenterList
    },
    site() {
      if (this.model.regionCode) {
        if (this.countryOptions && this.countryOptions.length > 0 && this.model.country) {
          return this.model.country.join(',')
        } else {
          return this.model.regionCode
        }
      }
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      if (this.model.id) {
        if (this.model.regionCode) {
          this.countryOptions = this.storeSiteOptions.find((s) => s.code === this.model.regionCode)?.sites || []
          this.model.country = record.site ? record.site.split(',') : []
        }
        if (this.merchantType === '1' && this.model.name) {
          this.handleSearch(this.model.name)
        }
      }
      this.authSkipUrl = ''
      this.getqueryTreeListByCurrDepart()
      this.getAllUsernameByOrgData()
      this.visible = true
    },
    //店铺名称输入校验
    validatorName(rule, value, callback) {
      if (value) {
        //外部客户做输入校验
        if (this.merchantType === '2') {
          if (new RegExp(/[\s\/*?"':<>|,.]/g).test(value)) {
            callback(new Error("店铺名称不能包含 、  / * ? '' ' :  <  > | 空格，. ，"))
          } else if (value.length < 2 || value.length > 32) {
            callback(new Error('店铺名称限制在2-32字符'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      } else {
        callback(new Error(`请${this.merchantType === '2' ? '输入' : '选择'}店铺名称`))
      }
    },
    //选择区域
    regionChange(value) {
      this.countryOptions = this.storeSiteOptions.find((s) => s.code === value)?.sites || []
      if (this.countryOptions && this.countryOptions.length === 1) {
        this.$set(this.model, 'country', [this.countryOptions[0].code])
      } else {
        this.$set(this.model, 'country', undefined)
      }
    },
    //点击授权
    authHandle() {
      if (!this.model.regionCode) {
        this.$message.warning('请选择区域')
      } else {
        getAction(this.url.authUrl, { region: this.model.regionCode, authId: this.model.authId }).then((res) => {
          if (res.success) {
            if (res.message) {
              window.open(res.message)
              this.authSkipUrl = res.message || ''
            }
          } else {
            this.$message.warning(res.message)
            this.authSkipUrl = ''
          }
        })
      }
    },
    //模糊搜索店铺名称
    handleSearch: simpleDebounce(function (value) {
      if (value) {
        putFormAction(this.url.queryStoreName, { storeName: value }).then((res) => {
          if (res.success) {
            this.storeNameData = res.result || []
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    }, 500),
    //操作说明
    previewHandle(){
       const pdfUrl =(this.model && this.model.id) ? 'http://file.languwin.com/pro/file/jeecg_demo/20250610/Amazon店铺授权步骤编辑.pdf':'http://file.languwin.com/pro/file/jeecg_demo/20250610/Amazon店铺授权步骤新增.pdf'
       const url =`${window._CONFIG['onlinePreviewDomainURL']}?url=`+encodeURIComponent(Base64.encode(pdfUrl))
       window.open(url, '_blank')
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    //获取店铺所属组织
    getqueryTreeListByCurrDepart() {
      getAction(this.url.queryTreeListByCurrDepart).then((res) => {
        if (res.success) {
          this.searchOptions = res.result || []
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //获取成本中心数据
    // getQueryAllByOrgCode(){
    //    getAction(this.url.queryAllByOrgCode).then(res=>{
    //     if(res.success){
    //      this.costCenterData = res.result ||[]
    //     }else{
    //       this.$message.warning(res.message)
    //     }
    //    })  
    // },
    //获取用户负责人数据
    getAllUsernameByOrgData() {
      getAction(this.url.getAllUsernameByOrg, { delFlag: 0, status: 1 }).then((res) => {
        if (res.success) {
          this.userDictOptions =res.result?.map((item) => {
              return { text: item, value: item }
            }) || []
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!that.authSkipUrl && !that.model.id) {
            that.$message.warning('请先进行授权')
            return
          }
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          // let record = Object.assign(this.model, {})
          // record['sites'] = this.model.site
          let { regionCode, country, ...parmaObj } = this.model
          parmaObj.site = that.site
          httpAction(httpurl, parmaObj, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
.required-icon{
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
}
/deep/.ant-alert.ant-alert-no-icon {
  margin-bottom: 10px;
  .ant-alert-message {
    color: #0e8ebe;
  }
}

.platform-name {
  display: flex;
  justify-content: space-between;

  .name-font {
    margin-left: 20px;
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
}

.tip {
  font-size: 12px;
  color: #f59a23;
  margin-left: 10px;
}
</style>